import 'dart:convert';
import '../models/home_info_model.dart';
import '../models/home_init_model.dart';
import '../manger/network_utils.dart';
import '../services/logger_service.dart';
import '../manger/user_manger.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';

// 封装返回结果
class LoadInfoResult {
  final bool success;
  final HomeInfoModelClassModel? homeInfoModelClassModel;
  LoadInfoResult({required this.success, this.homeInfoModelClassModel});
}

class LoadInitResult {
  final bool success;
  final HomeInitClassModel? homeInitModelClassModel;
  LoadInitResult({required this.success, this.homeInitModelClassModel});
}

// 单例管理器
class HomeInfoManager {
  static final HomeInfoManager _instance = HomeInfoManager._internal();
  factory HomeInfoManager() => _instance;
  HomeInfoManager._internal();

  // 全局数据
  HomeInfoModelClassModel? _homeInfoModelClassModel;
  HomeInitClassModel? _homeInitModelClassModel;

  // 获取全局数据方法
  HomeInfoModelClassModel? get homeInfoModel => _homeInfoModelClassModel;
  HomeInitClassModel? get homeInitModel => _homeInitModelClassModel;

  // 加载首页信息
  Future<LoadInfoResult> loadInfoData() async {
    try {
      final response = await NetworkUtils.post(
        RequestCmd.homeInfoen,
        body: null,
      );
      // LoggerService.logger.d(response);
      final model = HomeInfoModel.fromJson(response);
      if (model.code == 200 && model.data != null) {

        _homeInfoModelClassModel = model.data!;
        return LoadInfoResult(success: true, homeInfoModelClassModel: model.data);
      } else {
        return LoadInfoResult(success: false);
      }
    } catch (e) {
      return LoadInfoResult(success: false);
    }
  }

  // 加载初始化数据
  Future<LoadInitResult> loadInitData() async {
    try {
      final response = await NetworkUtils.post(
        isSimplifiedChinese() ? RequestCmd.homeInit : RequestCmd.homeIniten,
        body: null,
      );

      final model = HomeInitModel.fromJson(response);

      if (model.code == 200 && model.data != null) {
        _homeInitModelClassModel = model.data!;
        // 修改前代码有问题，修改为使用 ?. 进行条件访问
        final matchedCurrency = _homeInitModelClassModel?.currencyList.firstWhere(
          (element) => element.currencyId == _homeInitModelClassModel?.currency,
          // 传入必要参数创建实例
          orElse: () => CurrencyListModel( name: '', currencyId: 23 ,code: ""), 
        );
        const storage = FlutterSecureStorage();

        // 从Secure Storage中读取缓存的currency
        final cachedCurrency = await storage.read(key: 'cached_currency');
        if (cachedCurrency != null) {
          final decodedCurrency = jsonDecode(cachedCurrency);
          UserInfos.shared.currencyListModel = CurrencyListModel.fromJson(decodedCurrency);
        } else {
          // 如果没有缓存，使用当前的matchedCurrency
          UserInfos.shared.currencyListModel  = matchedCurrency;
          await storage.write(
            key: 'cached_currency',
            value: jsonEncode(matchedCurrency?.toJson()),
          );
        }
        return LoadInitResult(success: true, homeInitModelClassModel: model.data);
      } else {
        return LoadInitResult(success: false);
      }
    } catch (e) {
      LoggerService.logger.e('Error loading homeInit: $e');
      return LoadInitResult(success: false);
    }
  }
}
